import AlertComponet from "../../component/Alert";
import ContentBox from "../../component/ContentBox";
import SwitchTab from "../../component/SwitchTab";
import "./style.css";
import { useState, useEffect, createContext, useMemo } from "react";
import { landList, townList, selectList, getLandChart } from "../../api";
import { diva } from "../../global";
import Layout from "../../component/Layout";
import huatian from "../../component/idJson";
export const PlanInfoChildContext = createContext();
let val = 0;
const PlantInfo = () => {

  const [change, setChange] = useState(false);
  const [town, setTown] = useState([]);
  const [cancelBox, setCancelBox] = useState("");
  const [landData, setLandList] = useState([]);
  const [ownerData, setOwner] = useState([]);
  const [plantStatus, setPlantStatus] = useState([]);
  const [adopt, setAdopt] = useState([]);
  const [landChart, setLandChart] = useState([]);
  const [name, setName] = useState("");
  const [nameChange, setNameChange] = useState("");
  const getData = () => {
    landList()
      .then((res) => {
        setLandList(res.data.list);
      })
      .catch((err) => console.log(err));
    townList()
      .then((res) => {
        setTown(res.data.list);
      })
      .catch((err) => console.log(err));

    selectList()
      .then((res) => {
        setOwner(res.data.list.owner);
        setPlantStatus(res.data.list.plant);
        setAdopt(res.data.list.adopt);
      })
      .catch((err) => console.log(err));

    getLandChart()
      .then((res) => {
        setLandChart(res.data);
      })
      .catch((err) => console.log(err));
  };
  const getSearchInfo = (val) => {
    landList(val)
      .then((res) => {
        setLandList(res.data.list);
      })
      .catch((err) => console.log(err));
  };
  const [middleBoxVisible, setMiddleBoxVisible] = useState(false);

  const getChildrenValue = (val, name) => {
    if (val === 0 || name === undefined) {
      setMiddleBoxVisible(false);
      landList().then((res) => {
        setLandList(res.data.list);
      });
    }
    if (name && name !== "123") {
      diva.client
        ?.applyScene(`${name.substring(0, name.length - 1)}总地块`)
        .then(() => {
          name === "花田乡"
            ? huatian.huatian.map((item) => {
                changeDikuai(item.id, item.name,item.district_id,item.townId);
              })
            : name === "涂市镇"
            ? huatian.tushi.map((item) => {
                changeDikuai(item.id, item.name,item.district_id,item.townId);
              })
            : name === "南腰界镇"
            ? huatian.nanyao.map((item) => {
                changeDikuai(item.id, item.name,item.district_id,item.townId);
              })
            : name === "铜鼓镇"
            ? huatian.tonggu.map((item) => {
                changeDikuai(item.id, item.name,item.district_id,item.townId);
              })
            : name === "李溪镇"
            ? huatian.lixi.map((item) => {
                changeDikuai(item.id, item.name,item.district_id,item.townId);
              })
            : console.log(1);
        })
        .catch((err) => console.log(err));
      getLandChart({ t_id: val })
        .then((res) => {
          setLandChart(res.data);
        })
        .catch((err) => console.log(err));
        val=val;
      landList({ _v: val })
        .then((res) => {
          setLandList(res.data.list);
        })
        .catch((err) => console.log(err));
    }
  };

  const getPlantInfo = (val) => {
    diva.client
      ?.applyScene(0 + `${val + 1}地块`)
      .then(() => {})
      .catch((err) => console.log(err));
  };

  const changeDikuai = async (id, name,district_id,townId) => {
    const modal = await diva.client?.getEntityById(id);
    const listener = (event) => {
      diva.client
        ?.applyScene(name)
        .then(() => {})
        .catch((err) => console.log(err));
        landList({ _v: townId, district_id:district_id})
        .then((res) => {
          setLandList(res.data.list);
        })
    };
    modal?.addEventListener("click", listener);
    return () => {
      modal.setWebWidget(null);
    };
  };
  const getGroupId = async () => {
    diva.client
      ?.request("GetEntityIds", {
        group: "种植总览/涂市镇点位", // 资源列表中从根目录开始的路径
      })
      .then(async (res) => {
        const modal = await diva.client?.getEntityById(res.result[0]);
        const modal2 = await diva.client?.getEntityById(res.result[1]);

        const listener = (event) => {
          setNameChange("涂市镇");
          setName("涂市镇");
          setMiddleBoxVisible(true);
     
          diva.client
            ?.applyScene("涂市总地块")
            .then(() => {})
            .catch((err) => console.log(err));
        };
        modal?.addEventListener("click", listener);
        modal2?.addEventListener("click", listener);
      })
      .catch((err) => console.log(err));
    diva.client
      ?.request("GetEntityIds", {
        group: "种植总览/李溪镇点位", // 资源列表中从根目录开始的路径
      })
      .then(async (res) => {
        const modal = await diva.client?.getEntityById(res.result[0]);
        const modal2 = await diva.client?.getEntityById(res.result[1]);

        const listener = (event) => {
          setNameChange("李溪镇");
          setName("李溪镇");
          setMiddleBoxVisible(true);

          diva.client
            ?.applyScene("李溪总地块")
            .then(() => {})
            .catch((err) => console.log(err));
        };
        modal?.addEventListener("click", listener);
        modal2?.addEventListener("click", listener);
        return () => {
          modal?.removeEventListener("click", listener);
          modal2?.removeEventListener("click", listener);
        };
      })
      .catch((err) => console.log(err));
    diva.client
      ?.request("GetEntityIds", {
        group: "种植总览/铜鼓镇点位", // 资源列表中从根目录开始的路径
      })
      .then(async (res) => {
        const modal = await diva.client?.getEntityById(res.result[0]);
        const modal2 = await diva.client?.getEntityById(res.result[1]);

        const listener = (event) => {
          setNameChange("铜鼓镇");
          setName("铜鼓镇");
          setMiddleBoxVisible(true);

          diva.client
            ?.applyScene("铜鼓总地块")
            .then(() => {})
            .catch((err) => console.log(err));
        };
        modal?.addEventListener("click", listener);
        modal2?.addEventListener("click", listener);
      })
      .catch((err) => console.log(err));
    diva.client
      ?.request("GetEntityIds", {
        group: "种植总览/花田乡点位", // 资源列表中从根目录开始的路径
      })
      .then(async (res) => {
        const modal = await diva.client?.getEntityById(res.result[0]);
        const modal2 = await diva.client?.getEntityById(res.result[1]);

        const listener = (event) => {
          setNameChange("花田乡");
          setName("花田乡");
          setMiddleBoxVisible(true);

          diva.client
            ?.applyScene("花田总地块")
            .then(() => {})
            .catch((err) => console.log(err));
        };
        modal?.addEventListener("click", listener);
        modal2?.addEventListener("click", listener);
      })
      .catch((err) => console.log(err));
    diva.client
      ?.request("GetEntityIds", {
        group: "种植总览/南腰界镇点位", // 资源列表中从根目录开始的路径
      })
      .then(async (res) => {
        const modal = await diva.client?.getEntityById(res.result[0]);
        const modal2 = await diva.client?.getEntityById(res.result[1]);

        const listener = (event) => {
          setNameChange("南腰界镇");
          setName("南腰界镇");
          setMiddleBoxVisible(true);

          diva.client
            ?.applyScene("南腰界总地块")
            .then(() => {})
            .catch((err) => console.log(err));
        };
        modal?.addEventListener("click", listener);
        modal2?.addEventListener("click", listener);
      })
      .catch((err) => console.log(err));
  };

  const middleBoxName = (val) => {
    setNameChange(val);
  };
  const thisContent = useMemo(() => {
    return (
      <ContentBox
        setSelect={getSearchInfo}
        makeMiddleBox={middleBoxName}
        title={"种植管理"}
        plantIndex={getPlantInfo}
        selectFirst={[
          { title: "权属", options: ownerData, key: "owner" },
          { title: "种植", options: plantStatus, key: "plant" },
        ]}
        selectSecond={[{ title: "认养", options: adopt, key: "adopt" }]}
        tableListName={["耕地编号", "权属", "种植", "认养", "负责人"]}
        tableList={landData}
      />
    );
  });
  useEffect(() => {
    getData();
    getGroupId();
  }, []);

  return (
    <div>
      <SwitchTab
        index={2}
        layout={middleBoxVisible}
        title={town}
        setParentProps={getChildrenValue}
        nameChange={nameChange}
      />
      <div className="plantinfo-contanier">
        {/* <AlertComponet /> */}

        <div className="content-left">
          <ContentBox
            title={"耕地权属"}
            pieChart={landChart.adopt_status_chart}
            color={["#00B478", "#6495DC"]}
            PieIndex={0}
          />
          <ContentBox
            title={"种植状态"}
            pieChart={landChart.plant_status_chart}
            color={["#BE72B0", "#C26F66"]}
            PieIndex={0}
          />
          <ContentBox
            title={"认养状态"}
            pieChart={landChart.adopt_status_chart}
            color={["#00B478", "#6495DC"]}
            PieIndex={0}
          />
        </div>
        <div className="content-right">
          <ContentBox
            // makeMiddleBox={middleBoxName}
            // middleBoxName={name}
            title={"各乡镇耕地"}
            pieChart={landChart.plant_area_chart}
            color={[
              "rgb(180,60,60)",
              "rgb(139,0,180)",
              "rgb(50,205,100)",
              "rgb(70,130,180)",
              "rgb(252,132,82)",
            ]}
            PieIndex={1}
          />
          {thisContent}
        </div>
      </div>
    </div>
  );
};
export default PlantInfo;
